package com.divillysausages.dsair.util
{
	import flash.xml.XMLDocument;
	import flash.xml.XMLNode;
	import flash.xml.XMLNodeType;
	
	/**
	 * Utils for the String class
	 * @author Damian Connolly
	 */
	public class StringUtils
	{
		
		/**
		 * Converts the String to a Boolean. Ignores case
		 * @param string The String we're going to convert
		 * @return Returns true if the string is "true" or "1", false otherwise
		 */
		public static function toBoolean( string:String ):Boolean 
		{
			var s:String = string.toLowerCase();
			return ( s == "true" || s == "1" );
		}
		
		/**
		 * Trims whitespace from the start and end of a line
		 * @param s The string to check
		 * @return A String with the whitespace trimmed
		 */
		public static function trim( s:String ):String
		{
			return ( s != null ) ? s.replace( /^[\s|\t|\n]+|[\s|\t|\n]+$/gs, "" ) : "";
		}
		
		/**
		 * Checks if a string is empty or not. A String counts as empty if it's nothing but whitespace
		 * @param s The string to check
		 * @return If the string is empty or not
		 */
		public static function isEmpty( s:String ):Boolean
		{
			return StringUtils.trim( s ) == "";
		}
		
		/**
		 * Converts a String so all HTML entites are replaced so it can safely be displayed using
		 * the htmlText property of a TextField (e.g. "<" is converted to "&lt;")
		 * From http://www.razorberry.com/blog/archives/2007/11/02/converting-html-entities-in-as3/
		 * @param s The String to convert
		 * @return The escaped String
		 */
		public static function htmlEscape( s:String ):String
		{
			// NOTE: XMLNode is a legacy AS2 class
			return new XMLNode( XMLNodeType.TEXT_NODE, s ).toString();
		}
		
		/**
		 * Converts a String so all escaped HTML entites are replaced with their HTML counterparts
		 * (e.g. "&lt;" is converted to "<")
		 * From http://www.razorberry.com/blog/archives/2007/11/02/converting-html-entities-in-as3/
		 * @param s The String to convert
		 * @return The unescaped String
		 */
		public static function htmlUnescape( s:String ):String
		{
			// NOTE: XMLDocument is a legacy AS2 class
			return new XMLDocument( s ).firstChild.nodeValue;
		}

	}
}